﻿#if UNITY_IOS
using System.Runtime.InteropServices;
#endif
using System.Security.Cryptography;
using System.Text;
using UnityEngine;

namespace CGF
{
    public static class AppHelper
    {

        /// <summary>
        /// 仅在Unity主线程可取
        /// </summary>
        public static string GetAppPackageName()
        {
#if UNITY_EDITOR && UNITY_ANDROID
            return UnityEditor.PlayerSettings.GetApplicationIdentifier(UnityEditor.BuildTargetGroup.Android);
#elif UNITY_EDITOR && UNITY_IOS
            return UnityEditor.PlayerSettings.GetApplicationIdentifier(UnityEditor.BuildTargetGroup.iOS);
#elif UNITY_ANDROID
            AndroidJavaClass unityPlayer = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
            AndroidJavaObject currentActivity = unityPlayer.GetStatic<AndroidJavaObject>("currentActivity");
            try
            {
                AndroidJavaObject packageManager = currentActivity.Call<AndroidJavaObject>("getPackageManager");
                return currentActivity.Call<string>("getPackageName");
            }
            catch (System.Exception ex)
            {
                Debug.LogError("获取App Package Name出错：" + ex.Message);
            }
            return null;
#elif UNITY_IOS
            return _GetAppPackageName();
#else
            return null;
#endif
        }

        /// <summary>
        /// 仅在Unity主线程可取
        /// </summary>
        public static string GetAppVersionName()
        {
#if UNITY_EDITOR
            return UnityEditor.PlayerSettings.bundleVersion;
#elif UNITY_ANDROID
            try
            {
                using (AndroidJavaClass unityPlayer = new AndroidJavaClass("com.unity3d.player.UnityPlayer"))
                {
                    using (AndroidJavaObject currentActivity = unityPlayer.GetStatic<AndroidJavaObject>("currentActivity"))
                    {
                        using (AndroidJavaObject packageManager = currentActivity.Call<AndroidJavaObject>("getPackageManager"))
                        {
                            string packageName = currentActivity.Call<string>("getPackageName");
                            int packageInfoFlags = packageManager.GetStatic<int>("GET_CONFIGURATIONS");
                            using (AndroidJavaObject packageInfo = packageManager.Call<AndroidJavaObject>("getPackageInfo", packageName, packageInfoFlags))
                            {
                                return packageInfo.Get<string>("versionName");
                            }
                        }
                    }
                }
            }
            catch (System.Exception ex)
            {
                Debug.LogError("获取App Version Name出错：" + ex.Message);
            }
            return null;
#elif UNITY_IOS
            return _GetAppVersionName();
#else
            return "1.0";
#endif
        }

        /// <summary>
        /// 仅在Unity主线程可取
        /// </summary>
        public static int GetAppVersionCode()
        {
#if UNITY_EDITOR && UNITY_ANDROID
            return UnityEditor.PlayerSettings.Android.bundleVersionCode;
#elif UNITY_EDITOR && UNITY_IOS
            return int.Parse(UnityEditor.PlayerSettings.iOS.buildNumber);
#elif UNITY_ANDROID
            try
            {
                using (AndroidJavaClass unityPlayer = new AndroidJavaClass("com.unity3d.player.UnityPlayer"))
                {
                    using (AndroidJavaObject currentActivity = unityPlayer.GetStatic<AndroidJavaObject>("currentActivity"))
                    {
                        using (AndroidJavaObject packageManager = currentActivity.Call<AndroidJavaObject>("getPackageManager"))
                        {
                            string packageName = currentActivity.Call<string>("getPackageName");
                            int packageInfoFlags = packageManager.GetStatic<int>("GET_CONFIGURATIONS");
                            using (AndroidJavaObject packageInfo = packageManager.Call<AndroidJavaObject>("getPackageInfo", packageName, packageInfoFlags))
                            {
                                return packageInfo.Get<int>("versionCode");
                            }
                        }
                    }
                }
            }
            catch (System.Exception ex)
            {
                Debug.LogError("获取App Version Code出错：" + ex.Message);
            }
            return 1;
#elif UNITY_IOS
            return _GetAppVersionCode();
#else
            return 1;
#endif
        }

        /// <summary>
        /// 获取apk签名指纹SHA1
        /// </summary>
        public static string GetApkSignSHA1()
        {
#if UNITY_ANDROID && !UNITY_EDITOR
            // 获取当前的Activity
            AndroidJavaClass unityPlayer = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
            AndroidJavaObject currentActivity = unityPlayer.GetStatic<AndroidJavaObject>("currentActivity");
            try
            {
                // 获取PackageManager
                AndroidJavaObject packageManager = currentActivity.Call<AndroidJavaObject>("getPackageManager");
                // 获取应用程序的包名
                string packageName = currentActivity.Call<string>("getPackageName");
                // 获取应用程序的签名信息
                int GET_SIGNATURES = 0x40;
                AndroidJavaObject packageInfo = packageManager.Call<AndroidJavaObject>("getPackageInfo", packageName, GET_SIGNATURES);
                AndroidJavaObject[] signatures = packageInfo.Get<AndroidJavaObject[]>("signatures");
                // 计算SHA1签名指纹
                using (AndroidJavaClass messageDigestClass = new AndroidJavaClass("java.security.MessageDigest"))
                {
                    AndroidJavaObject md = messageDigestClass.CallStatic<AndroidJavaObject>("getInstance", "SHA1");
                    byte[] signatureBytes = signatures[0].Call<byte[]>("toByteArray");
                    byte[] digestBytes = md.Call<byte[]>("digest", signatureBytes);
                    // 将字节数组转换为十六进制字符串
                    System.Text.StringBuilder sb = new System.Text.StringBuilder();
                    for (int i = 0; i < digestBytes.Length; i++)
                    {
                        if (i > 0)
                        {
                            sb.Append(":");
                        }
                        sb.Append(digestBytes[i].ToString("X2"));
                    }
                    return sb.ToString();
                }
            }
            catch (System.Exception ex)
            {
                Debug.LogError("获取SHA1签名指纹信息出错：" + ex.Message);
            }
#endif
            return null;
        }

        /// <summary>
        /// 获取apk签名MD5
        /// </summary>
        public static string GetApkSignMD5()
        {
#if UNITY_ANDROID && !UNITY_EDITOR
            AndroidJavaClass unityPlayer = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
            AndroidJavaObject currentActivity = unityPlayer.GetStatic<AndroidJavaObject>("currentActivity");
            try
            {
                AndroidJavaObject packageManager = currentActivity.Call<AndroidJavaObject>("getPackageManager");
                string packageName = currentActivity.Call<string>("getPackageName");
                int GET_SIGNATURES = 0x40;
                AndroidJavaObject packageInfo = packageManager.Call<AndroidJavaObject>("getPackageInfo", packageName, GET_SIGNATURES);
                AndroidJavaObject[] signatures = packageInfo.Get<AndroidJavaObject[]>("signatures");
                using (AndroidJavaObject sig = signatures[0])
                {
                    byte[] cert = sig.Call<byte[]>("toByteArray");
                    using (MD5 md5 = MD5.Create())
                    {
                        byte[] digestBytes = md5.ComputeHash(cert);

                        StringBuilder sb = new StringBuilder();
                        for (int i = 0; i < digestBytes.Length; i++)
                        {
                            if (i > 0)
                            {
                                sb.Append(":");
                            }
                            sb.Append(digestBytes[i].ToString("X2"));
                        }
                        return sb.ToString();
                    }
                }
            }
            catch (System.Exception ex)
            {
                Debug.LogError("获取MD5签名指纹信息出错：" + ex.Message);
            }
#endif
            return null;
        }

#if UNITY_IOS
        [DllImport("__Internal")]
        static extern string _GetAppPackageName();

        [DllImport("__Internal")]
        static extern string _GetAppVersionName();

        [DllImport("__Internal")]
        static extern int _GetAppVersionCode();
#endif
    }
}